package org.muxiao.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.muxiao.seckill.exception.GlobalException;
import org.muxiao.seckill.mapper.UserMapper;
import org.muxiao.seckill.pojo.User;
import org.muxiao.seckill.service.UserService;
import org.muxiao.seckill.util.CookieUtil;
import org.muxiao.seckill.util.MD5Util;
import org.muxiao.seckill.util.UUIDUtil;
import org.muxiao.seckill.vo.LoginVo;
import org.muxiao.seckill.vo.RespBean;
import org.muxiao.seckill.vo.RespBeanEnum;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务实现类
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 用户登录校验
     *
     * @param loginVo
     * @param request
     * @param response
     * @return
     */
    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {

        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();


        User user = this.baseMapper.selectById(mobile);
        if (null == user) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        String dbPass = MD5Util.midPassToDBPass(password, user.getSlat());
        if (!dbPass.equals(user.getPassword())) {
            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
        }

        //给用户生成 ticket
        String ticket = UUIDUtil.uuid();

        //将ticket保存到 Cookie
        CookieUtil.setCookie(request, response, "userTicket", ticket);

        //实现分布式session, 把登录的用户存放到Redis
        System.out.println("使用的 redisTemplate-->" + redisTemplate.hashCode());
        redisTemplate.opsForValue().set("user:" + ticket, user, 12, TimeUnit.HOURS);

        return RespBean.success(ticket);
    }

    /**
     * 根据用户的 ticket 获取用户信息
     *
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {

        if (StringUtils.isBlank(userTicket)) {
            return null;
        }

        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if (null != user) {
            //CookieUtil.setCookie(request, response, "userTicket", userTicket);
            redisTemplate.opsForValue().set("user:" + userTicket, user, 12, TimeUnit.HOURS);
        }

        return user;
    }

}
